package org.hashdb.client.view;

import org.hashdb.client.config.AppConfig;
import org.hashdb.client.constans.Net;
import org.hashdb.client.exception.ArgsFormatException;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Date: 2023/12/2 16:44
 *
 * @author huanyuMake-pecdle
 * @version 0.0.1
 */
public abstract class CmdArgsPage implements Page {

    protected static final AppConfig config = AppConfig.getInstance();

    public void show(String @NotNull [] args) throws IOException {
        HashMap<String, String> map = new HashMap<>();
        for (String arg : args) {
            String[] split = arg.split("=");
            if (split.length == 1) {
                map.put(split[0], Boolean.TRUE.toString());
            }
            if (split.length != 2) {
                continue;
//                throw new ArgsFormatException("illegal command args format '" + arg + "'. it should be like 'key=value' pair");
            }
            map.put(split[0], split[1]);
        }
        String host = map.get("host");
        if (host != null) {
            if (!host.matches(Net.HOST_REGEX)) {
                throw new ArgsFormatException("host should be IPv4 format. illegal host '" + host + "'");
            }
            config.setHost(host);
        }
        String portStr = map.get("port");
        if (portStr != null) {
            int port;
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException e) {
                throw new ArgsFormatException("port should be an integer between 0 and 65535");
            }
            if (port < 0 || port > 65535) {
                throw new ArgsFormatException("port should between 0 and 65535. illegal port '" + portStr + "'");
            }
            config.setPort(port);
        }
        show(map);
    }

    abstract void show(Map<String, String> options) throws IOException;
}
